3 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
26 * Query module to perform full text search within wiki titles and content
30 class ApiQuerySearch
extends ApiQueryGeneratorBase
{
33 /** @var array list of api allowed params */
34 private $allowedParams;
36 public function __construct( ApiQuery
$query, $moduleName ) {
37 parent
::__construct( $query, $moduleName, 'sr' );
40 public function execute() {
44 public function executeGenerator( $resultPageSet ) {
45 $this->run( $resultPageSet );
49 * @param ApiPageSet $resultPageSet
52 private function run( $resultPageSet = null ) {
53 $params = $this->extractRequestParams();
56 $query = $params['search'];
57 $what = $params['what'];
58 $interwiki = $params['interwiki'];
59 $searchInfo = array_flip( $params['info'] );
60 $prop = array_flip( $params['prop'] );
62 // Create search engine instance and set options
63 $search = $this->buildSearchEngine( $params );
64 if ( isset( $params['sort'] ) ) {
65 $search->setSort( $params['sort'] );
67 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
68 $search->setFeatureData( 'interwiki', (bool)$interwiki );
70 $nquery = $search->replacePrefixes( $query );
71 if ( $nquery !== $query ) {
73 wfDeprecated( 'SearchEngine::replacePrefixes() (overridden by ' .
74 get_class( $search ) . ')', '1.32' );
76 // Perform the actual search
77 if ( $what == 'text' ) {
78 $matches = $search->searchText( $query );
79 } elseif ( $what == 'title' ) {
80 $matches = $search->searchTitle( $query );
81 } elseif ( $what == 'nearmatch' ) {
82 // near matches must receive the user input as provided, otherwise
83 // the near matches within namespaces are lost.
84 $matches = $search->getNearMatcher( $this->getConfig() )
85 ->getNearMatchResultSet( $params['search'] );
87 // We default to title searches; this is a terrible legacy
88 // of the way we initially set up the MySQL fulltext-based
89 // search engine with separate title and text fields.
90 // In the future, the default should be for a combined index.
92 $matches = $search->searchTitle( $query );
94 // Not all search engines support a separate title search,
95 // for instance the Lucene-based engine we use on Wikipedia.
96 // In this case, fall back to full-text search (which will
97 // include titles in it!)
98 if ( is_null( $matches ) ) {
100 $matches = $search->searchText( $query );
104 if ( $matches instanceof Status
) {
106 $matches = $status->getValue();
112 if ( $status->isOK() ) {
113 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
114 $this->getModuleName(),
118 $this->dieStatus( $status );
120 } elseif ( is_null( $matches ) ) {
121 $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
124 if ( $resultPageSet === null ) {
125 $apiResult = $this->getResult();
126 // Add search meta data to result
127 if ( isset( $searchInfo['totalhits'] ) ) {
128 $totalhits = $matches->getTotalHits();
129 if ( $totalhits !== null ) {
130 $apiResult->addValue( [ 'query', 'searchinfo' ],
131 'totalhits', $totalhits );
134 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
135 $apiResult->addValue( [ 'query', 'searchinfo' ],
136 'suggestion', $matches->getSuggestionQuery() );
137 $apiResult->addValue( [ 'query', 'searchinfo' ],
138 'suggestionsnippet', $matches->getSuggestionSnippet() );
140 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
141 $apiResult->addValue( [ 'query', 'searchinfo' ],
142 'rewrittenquery', $matches->getQueryAfterRewrite() );
143 $apiResult->addValue( [ 'query', 'searchinfo' ],
144 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
148 // Add the search results to the result
149 $terms = MediaWikiServices
::getInstance()->getContentLanguage()->
150 convertForSearchResult( $matches->termMatches() );
154 if ( $matches->hasMoreResults() ) {
155 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
158 foreach ( $matches as $result ) {
160 // Silently skip broken and missing titles
161 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
165 if ( $resultPageSet === null ) {
166 $vals = $this->getSearchResultData( $result, $prop, $terms );
168 // Add item to results and see whether it fits
169 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
171 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
176 $titles[] = $result->getTitle();
180 // Here we assume interwiki results do not count with
181 // regular search results. We may want to reconsider this
182 // if we ever return a lot of interwiki results or want pagination
184 // Interwiki results inside main result set
185 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
186 if ( $canAddInterwiki ) {
187 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
188 SearchResultSet
::INLINE_RESULTS
);
191 // Interwiki results outside main result set
192 if ( $interwiki && $resultPageSet === null ) {
193 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
194 SearchResultSet
::SECONDARY_RESULTS
);
197 if ( $resultPageSet === null ) {
198 $apiResult->addIndexedTagName( [
199 'query', $this->getModuleName()
202 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
203 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
204 $current['index'] = $new['index'];
208 $resultPageSet->populateFromTitles( $titles );
209 $offset = $params['offset'] +
1;
210 foreach ( $titles as $index => $title ) {
211 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
217 * Assemble search result data.
218 * @param SearchResult $result Search result
219 * @param array $prop Props to extract (as keys)
220 * @param array $terms Terms list
221 * @return array|null Result data or null if result is broken in some way.
223 private function getSearchResultData( SearchResult
$result, $prop, $terms ) {
224 // Silently skip broken and missing titles
225 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
231 $title = $result->getTitle();
232 ApiQueryBase
::addTitleInfo( $vals, $title );
233 $vals['pageid'] = $title->getArticleID();
235 if ( isset( $prop['size'] ) ) {
236 $vals['size'] = $result->getByteSize();
238 if ( isset( $prop['wordcount'] ) ) {
239 $vals['wordcount'] = $result->getWordCount();
241 if ( isset( $prop['snippet'] ) ) {
242 $vals['snippet'] = $result->getTextSnippet( $terms );
244 if ( isset( $prop['timestamp'] ) ) {
245 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
247 if ( isset( $prop['titlesnippet'] ) ) {
248 $vals['titlesnippet'] = $result->getTitleSnippet();
250 if ( isset( $prop['categorysnippet'] ) ) {
251 $vals['categorysnippet'] = $result->getCategorySnippet();
253 if ( !is_null( $result->getRedirectTitle() ) ) {
254 if ( isset( $prop['redirecttitle'] ) ) {
255 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
257 if ( isset( $prop['redirectsnippet'] ) ) {
258 $vals['redirectsnippet'] = $result->getRedirectSnippet();
261 if ( !is_null( $result->getSectionTitle() ) ) {
262 if ( isset( $prop['sectiontitle'] ) ) {
263 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
265 if ( isset( $prop['sectionsnippet'] ) ) {
266 $vals['sectionsnippet'] = $result->getSectionSnippet();
269 if ( isset( $prop['isfilematch'] ) ) {
270 $vals['isfilematch'] = $result->isFileMatch();
273 if ( isset( $prop['extensiondata'] ) ) {
274 $extra = $result->getExtensionData();
275 // Add augmented data to the result. The data would be organized as a map:
276 // augmentorName => data
278 $vals['extensiondata'] = ApiResult
::addMetadataToResultVars( $extra );
286 * Add interwiki results as a section in query results.
287 * @param SearchResultSet $matches
288 * @param ApiResult $apiResult
289 * @param array $prop Props to extract (as keys)
290 * @param array $terms Terms list
291 * @param string $section Section name where results would go
292 * @param int $type Interwiki result type
293 * @return int|null Number of total hits in the data or null if none was produced
295 private function addInterwikiResults(
296 SearchResultSet
$matches, ApiResult
$apiResult, $prop,
297 $terms, $section, $type
300 if ( $matches->hasInterwikiResults( $type ) ) {
301 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
302 // Include number of results if requested
303 $totalhits +
= $interwikiMatches->getTotalHits();
305 foreach ( $interwikiMatches as $result ) {
306 $title = $result->getTitle();
307 $vals = $this->getSearchResultData( $result, $prop, $terms );
309 $vals['namespace'] = $result->getInterwikiNamespaceText();
310 $vals['title'] = $title->getText();
311 $vals['url'] = $title->getFullURL();
313 // Add item to results and see whether it fits
314 $fit = $apiResult->addValue( [
316 $section . $this->getModuleName(),
317 $result->getInterwikiPrefix()
321 // We hit the limit. We can't really provide any meaningful
322 // pagination info so just bail out
327 if ( $totalhits !== null ) {
328 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
329 $apiResult->addIndexedTagName( [
330 'query', $section . $this->getModuleName()
337 public function getCacheMode( $params ) {
341 public function getAllowedParams() {
342 if ( $this->allowedParams
!== null ) {
343 return $this->allowedParams
;
346 $this->allowedParams
= $this->buildCommonApiParams() +
[
348 ApiBase
::PARAM_TYPE
=> [
355 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
356 ApiBase
::PARAM_TYPE
=> [
361 ApiBase
::PARAM_ISMULTI
=> true,
364 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
365 ApiBase
::PARAM_TYPE
=> [
377 'score', // deprecated
378 'hasrelated', // deprecated
381 ApiBase
::PARAM_ISMULTI
=> true,
382 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
383 ApiBase
::PARAM_DEPRECATED_VALUES
=> [
388 'interwiki' => false,
389 'enablerewrites' => false,
392 // If we have more than one engine the list of available sorts is
393 // difficult to represent. For now don't expose it.
394 $services = MediaWiki\MediaWikiServices
::getInstance();
395 $alternatives = $services
396 ->getSearchEngineConfig()
398 if ( count( $alternatives ) == 1 ) {
399 $this->allowedParams
['sort'] = [
400 ApiBase
::PARAM_DFLT
=> 'relevance',
401 ApiBase
::PARAM_TYPE
=> $services
407 return $this->allowedParams
;
410 public function getSearchProfileParams() {
413 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
414 'help-message' => 'apihelp-query+search-param-qiprofile',
419 protected function getExamplesMessages() {
421 'action=query&list=search&srsearch=meaning'
422 => 'apihelp-query+search-example-simple',
423 'action=query&list=search&srwhat=text&srsearch=meaning'
424 => 'apihelp-query+search-example-text',
425 'action=query&generator=search&gsrsearch=meaning&prop=info'
426 => 'apihelp-query+search-example-generator',
430 public function getHelpUrls() {
431 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Search';